package com.usian.listerner;

import com.usian.service.SearchItemService;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class SearchMQListener {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private SearchItemService searchItemService;
/*
 * 监听者接收消息三要素：
 *  1、queue队列明durable = "true"是做持久化的
 *  2、exchange交换器名
 *  3、routing key路由的key
 */
@RabbitListener(bindings = @QueueBinding(
        value = @Queue(value="search_queue",durable = "true"),
        exchange = @Exchange(value="item_exchage",type= ExchangeTypes.TOPIC),
        key= {"item.add"}
))
    public void listenadd(String msg) throws IOException {
        System.out.println("接收的消息是"+msg);
        //接收到消息执行添加es的方法且返回一个int做是否成功的判断
        int result = searchItemService.insertDocument(msg);
        //如果判断失败报异常
        if(result>0){
            throw new RuntimeException("同步失败");
        }
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value="search_queue",durable = "true"),
            exchange = @Exchange(value="item_exchage",type= ExchangeTypes.TOPIC),
            key= {"item.update"}
    ))
    public void listenupdate(String msg) throws IOException {
        System.out.println("接收的消息是"+msg);
        //接收到消息执行添加es的方法且返回一个int做是否成功的判断
        int result = searchItemService.updateDocument(msg);
        //如果判断失败报异常
        if(result!=0){
            throw new RuntimeException("同步失败");
        }
    }
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value="search_queue",durable = "true"),
            exchange = @Exchange(value="item_exchage",type= ExchangeTypes.TOPIC),
            key= {"item.delete"}
    ))
    public void listendelete(String msg) throws IOException {
        System.out.println("接收的消息是"+msg);
        //接收到消息执行添加es的方法且返回一个int做是否成功的判断
        int result = searchItemService.deleteDocument(msg);
        //如果判断失败报异常
        if(result!=0){
            throw new RuntimeException("同步失败");
        }
    }
}
